import requests
import json


def open_url(url):
    nameID = url.split('=')[1]
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36",
        "referer": "https://music.163.com"
    }
    data = {
        "params": "BEHhnfg5V0r7dbXfxcEUEs/WFPXShib778VClI5bvPwG0OeuIH7HPwU17zgk+fBm1uvFQXAyKyi/wGjWR/pHe22WldVOhBGliKCOei+8rbKeESgze+JoG/uIq8Rhzsum7zywdx6OjK4hqm21mO30HLKIfNc9ZJ0GEdcgdS+VCXQOdmccxwtot/qcmOIb4FKy",
        "encSecKey": "4ce93300df4e8eccfcf6a390f8b6985b10ac903e4af7764cbd73b177a16e1b927942156c6c2220f47eea62c7ba5329069b6d96c5a316b36f1f81dcbfd06f3a2e86088fac64d6c059c8a59dce42ce07dc59ef2dd546c038bea917ef871387efe427cb1a4181d37dcade75cfcaafa57dea14d7cb95de4e11875b03871dd4983236"
    }
    targetUrl = "https://music.163.com/api/v1/resource/comments/R_SO_4_{}?csrf_token=".format(nameID)
    res = requests.get(targetUrl, headers=headers, data=data)
    return res


def main():
    URL = input("请输入链接地址：")
    #URL = "https://music.163.com/#/song?id=1346111053"
    res = open_url(URL)
    # 解析json
    AllJson = json.loads(res.text)
    hotComments = AllJson['hotComments']
    # 输出
    with open("评论.txt", "w", encoding="utf8") as file:
      for item in hotComments:
        # 输出评论者
        file.write(item['user']['nickname'] + "：\n\n")
        # 输出评论
        file.write(item['content'])
        file.write("\n--------------------\n")
    print("评论抓取完成")


if __name__ == "__main__":
    main()
